import { Component, OnInit, ViewChild, Type } from '@angular/core';
import { Router } from '@angular/router';
import { STComponent, STColumn, STChange, STData } from '@delon/abc/st';
import {
  SFComponent,
  SFDateWidgetSchema,
  SFRadioWidgetSchema,
  SFSchema,
  SFSchemaEnum,
  SFSelectWidgetSchema,
  SFUISchema
} from '@delon/form';
import { SearchDrawerService, ShipperBaseService } from '@shared';
import { NzModalService } from 'ng-zorro-antd/modal';
import { of } from 'rxjs';
import { map } from 'rxjs/operators';
import { BasicTableComponent } from 'src/app/routes/commom';
import { WaybillManagementServe } from '../../services/waybill-management.service';

@Component({
  selector: 'app-abnormal-appear',
  templateUrl: './abnormal-appear.component.html',
  styleUrls: ['../../../commom/less/commom-table.less', './abnormal-appear.component.less']
})
export class WaybillManagementAbnormalAppearComponent extends BasicTableComponent implements OnInit {
  @ViewChild('detailModal', { static: true })
  detailModal!: any;
  @ViewChild('replyModal', { static: true })
  replyModal!: any;
  ui: SFUISchema = {};
  ui2: SFUISchema = {};
  addSchema: SFSchema = {};
  editText = '';
  formData: any;
  isVisible = false;
  edit = false;
  editId = false;
  selectedIndex = 0;
  isLoading: boolean = false;
  tabs = {
    stayQuantity: 0,
    receivedQuantity: 0
  };

  columns: STColumn[] = [
    {
      title: '序号',
      className: 'text-center',
      width: '60px',
      format: (item: STData, col: STColumn, idx: number) => {
        return ((this.st.pi -1) * this.st.ps) + idx + 1 + ''
      } 
    },
    {
      title: '异常编号',
      index: 'exceptionCode',
      width: '180px',
      className: 'text-left',
      type: 'link',
      click: item => this.reviewDetailAction(item)
    },
    { title: '异常类型', index: 'exceptionTypeLabel', width: '180px', className: 'text-left' },
    {
      title: '关联运单号',
      index: 'wayBillCode',
      width: '180px',
      className: 'text-left',
      type: 'link',
      click: item => this.routeToBill(item)
    },
    { title: '网络货运人', index: 'enterpriseInfoName', width: '250px', className: 'text-left' },
    { title: '货主', index: 'shipperAppUserName', width: '250px', className: 'text-left' },
    { title: '装货地', index: 'loadingAddressArr', width: '220px', className: 'text-left' },
    { title: '卸货地', index: 'unloadingAddressArr', width: '220px', className: 'text-left' },
    { title: '承运司机', index: 'driver', width: '250px', className: 'text-left' },
    { title: '异常信息', index: 'exceptionContent', width: '250px', className: 'text-left' },
    { title: '异常图片', render: 'exceptionCertificateFirstFilePath', width: '300px', className: 'text-left' },
    { title: '上报时间', index: 'createTime', width: '180px', className: 'text-center' },
    { title: '回复人', index: 'replyAppUserName', width: '180px', className: 'text-left', iif: _ => this.selectedIndex === 1 },
    { title: '回复时间', index: 'replyTime', width: '180px', className: 'text-left', iif: _ => this.selectedIndex === 1 },
    {
      title: '操作',
      fixed: 'right',
      width: '100px',
      iif: _ => this.selectedIndex === 0,
      className: 'text-center',
      buttons: [{ text: '回复', click: item => this.replyAction(item) }]
    }
  ];
  resourceStatus: number | undefined;

  get reqParams() {
    return {
      ...this.sf?.value,
      replyStatus: this.resourceStatus || 0,
      reportingTime: {
        start: this.sf?.value?.reportingTime?.[0] || '',
        end: this.sf?.value?.reportingTime?.[1] || ''
      }
    };
  }
  get reqParams2() {
    return {
      ...this.sf?.value,
      replyStatus: this.resourceStatus || 1,
      reportingTime: {
        start: this.sf?.value?.reportingTime?.[0] || '',
        end: this.sf?.value?.reportingTime?.[1] || ''
      }
    };
  }
  itemInfo: any = {};
  replyContent = '';
  constructor(
    public service: WaybillManagementServe,
    private nzModalService: NzModalService,
    public shipperSrv: ShipperBaseService,
    private router: Router,
    public searchDrawerService: SearchDrawerService
  ) {
    super(searchDrawerService);
  }

  ngOnInit(): void {
    this.initSF();
    this.getGoodsSourceStatistical();
  }

  reviewDetailAction(item: any) {
    this.itemInfo = {};
    this.service.request(`${this.service.$api_get_listOperate_detail}${item.id}`, {}, 'GET').subscribe(res => {
      if (res) {
        this.itemInfo = res;
        const modal = this.nzModalService.create({
          nzContent: this.detailModal,
          nzWidth: 600,
          nzTitle: '异常详情',
          nzFooter: []
        });
      }
    });
  }

  replyAction(item: any) {
    this.replyContent = '';
    const modal = this.nzModalService.create({
      nzContent: this.replyModal,
      nzTitle: '回复',
      nzOnOk: () => {
        if (!this.replyContent) {
          this.service.msgSrv.warning('请填写回复内容');
          return false;
        }
        this.service
          .request(this.service.$api_operate_reply, [
            {
              id: item.id,
              replyContent: this.replyContent
            }
          ])
          .subscribe(res => {
            if (res) {
              this.service.msgSrv.success('回复成功');
              this.st.load(1);
              this.getGoodsSourceStatistical();
            }
          });
        return true;
      }
    });
  }

  routeToBill(item: any) {
    if (item.billType === '1') {
      this.router.navigate([`/waybill-management/vehicle/vehicle-detail/${item.wayBillId}`]);
    } else {
      this.router.navigate([`/waybill-management/bulk/bulk-detail/${item.wayBillId}`]);
    }
  }

  initSF() {
    this.schema = {
      properties: {
        exceptionCode: {
          type: 'string',
          title: '异常编号',
          ui: { placeholder: '请输入' }
        },
        wayBillCode: {
          type: 'string',
          title: '运单号',
          ui: { placeholder: '请输入' }
        },
        exceptionType: {
          title: '异常类型',
          type: 'string',
          ui: {
            widget: 'dict-select',
            containsAllLable: true,
            params: { dictKey: 'exception:report:type' }
          } as SFSelectWidgetSchema
        },
        shipperAppUserId: {
          type: 'string',
          title: '货主',
          ui: {
            widget: 'select',
            serverSearch: true,
            searchDebounceTime: 300,
            searchLoadingText: '搜索中...',
            allowClear: true,
            onSearch: (q: any) => {
              let str = q.replace(/^\s+|\s+$/g, '');
              if (str) {
                return this.service
                  .request(this.service.$api_enterpriceList, { enterpriseName: str })
                  .pipe(map((res: any) => (res as any[]).map(i => ({ label: i.enterpriseName, value: i.id } as SFSchemaEnum))))
                  .toPromise();
              } else {
                return of([]);
              }
            },
            change: (q: any) => {
              this.getRegionCode(q);
            }
          } as SFSelectWidgetSchema
        },
        enterpriseProjectId: {
          type: 'string',
          title: '所属项目',
          ui: {
            widget: 'select',
            placeholder: '请先选择货主'
          } as SFSelectWidgetSchema
        },
        driverName: {
          title: '承运司机',
          type: 'string'
        },
        carNo: {
          title: '车牌号',
          type: 'string'
        },
        reportingTime: {
          title: '上报时间',
          type: 'string',
          ui: {
            widget: 'date',
            mode: 'range',
            format: 'yyyy-MM-dd'
          } as SFDateWidgetSchema
        },
        enterpriseInfoId: {
          type: 'string',
          title: '网络货运人',
          ui: {
            widget: 'select',
            placeholder: '请选择',
            allowClear: true,
            asyncData: () => this.shipperSrv.getNetworkFreightForwarder()
          }
        }
      }
    };
    this.ui = { '*': { spanLabelFixed: 110, grid: { span: 8, gutter: 4 } } };
  }
  selectChange(e: number) {
    console.log(e);
    this.resourceStatus = e;
    setTimeout(() => {
      this?.st?.load(1);
      this.st.resetColumns();
    }, 0);
  }
  getGoodsSourceStatistical() {
    this.tabs = {
      stayQuantity: 0,
      receivedQuantity: 0
    };
    const params: any = Object.assign({}, this.reqParams || {});
    delete params.replyStatus;
    this.service.request(this.service.$api_get_listOperateStatus, params).subscribe(res => {
      if (res) {
        res.forEach((element: any) => {
          if (element.replyStatus === '1') {
            this.tabs.receivedQuantity = element.quantity;
          } else if (element.replyStatus === '0') {
            this.tabs.stayQuantity = element.quantity;
          }
        });
      }
    });
  }
  search() {
    console.log(this.st);

    this.st?.load(1);
    this.getGoodsSourceStatistical();
  }
  /**
   * 重置表单
   */
  resetSF() {
    this.sf.reset();
    this.isLoading = true;
  }
  // 获取城市列表
  getRegionCode(regionCode: any) {
    console.log(regionCode);
    return this.service
      .request(this.service.$api_get_enterprise_project, { id: regionCode })
      .pipe(
        map(res =>
          res.map((item: any) => ({
            label: item.projectName,
            value: item.id
          }))
        )
      )
      .subscribe(res => {
        this.sf.getProperty('/enterpriseProjectId')!.schema.enum = res;
        this.sf.getProperty('/enterpriseProjectId')!.widget.reset(res);
        // if (this.enterpriseProjectIds) {
        //   this.sf1.setValue('/enterpriseProjectId', this.enterpriseProjectIds);
        // }
      });
  }
}
